package com.ilovepostcard;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ilovepostcard.controller.ServerAsyncTask;
import com.ilovepostcard.controller.UserController;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.model.Message;
import com.ilovepostcard.model.Postcard;
import com.ilovepostcard.model.User;
import com.ilovepostcard.utils.DrawableManager;
import com.ilovepostcard.utils.Utils;
import com.ilovepostcard.view.PostcardWidget;

public class MessageActivity extends MenuActivity {
	
	ListView list;
	private int page = 0;
	ArrayList<Message> messages = new ArrayList<Message>();
	MessageAdapter adapter;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_message);
		init();
	}
	
	private void init()
	{	
		list = (ListView)findViewById(R.id.message_list); 
		adapter = new MessageAdapter(messages);
		list.setAdapter(adapter);
		list.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                final Message message = messages.get(position);
                Utils.showConfirmDialog(MessageActivity.this, "真的要删除这条消息吗？", new Runnable() {
                    
                    @Override
                    public void run() {
                        new ServerAsyncTask(MessageActivity.this) {
                            
                            @Override
                            protected void onSuccess(PostcardResult result) {
                                messages.remove(message);
                                adapter.notifyDataSetChanged();
                            }
                            
                            @Override
                            protected PostcardResult doRequest() {
                                return ServerFactory.getServer().deleteMessage(message.ReceiverID, message.MessageID);
                            }
                        }.execute();
                    }
                }, new Runnable() {
                    
                    @Override
                    public void run() {
                        
                    }
                });
                return true;
            }
		    
        });
		new ServerAsyncTask(MessageActivity.this) {
            
            @Override
            protected void onSuccess(PostcardResult result) {
                page++;
                messages.addAll(result.getMessageList());
                adapter.notifyDataSetChanged();
            }
            
            @Override
            protected PostcardResult doRequest() {
                User loginUser = UserController.getLoginUser(MessageActivity.this);
                return ServerFactory.getServer().listMessage(loginUser.UserID, (page+1), 15);
            }
        }.execute();
		
	}
	
	
	
	class MessageAdapter extends BaseAdapter
	{

		ArrayList<Message> list;
		
		
		public MessageAdapter(ArrayList<Message> list) {
            super();
            this.list = list;
        }

        @Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			
			if(convertView == null)
			{
				convertView = LayoutInflater.from(MessageActivity.this).inflate(R.layout.search_message_item, null);
			}
			
			final ImageView icon = (ImageView) convertView.findViewById(R.id.icon);
			final TextView nickname = (TextView) convertView.findViewById(R.id.search_name);
			final TextView date = (TextView) convertView.findViewById(R.id.search_time);
			final TextView content = (TextView) convertView.findViewById(R.id.search_count);
			final PostcardWidget widget = (PostcardWidget) convertView.findViewById(R.id.postcard_widget);
			final Message message = messages.get(position);
			
//			icon.setImageResource(0);
			icon.setImageBitmap(null);
			new ServerAsyncTask(MessageActivity.this) {
                
			    protected boolean isShowDialog() {
			        return false;
			    }
			    
                @Override
                protected void onSuccess(PostcardResult result) {
                    String url = result.getUserHeadImgUrl();
                    DrawableManager.getInstance().fetchDrawableOnThread(url, icon, false);
                }
                
                @Override
                protected PostcardResult doRequest() {
                    return ServerFactory.getServer().getUserHeadImg(message.SenderID);
                }
            }.execute();
            nickname.setText(message.SenderName);
            if (1 == message.MessageType) {
                content.setText("TA关注你啦");
                widget.setVisibility(View.GONE);
                widget.setOnClickListener(null);
            } else if (2 == message.MessageType) {
                content.setText("TA觉得你作品很赞");
                new ServerAsyncTask(MessageActivity.this) {
                    
                    protected boolean isShowDialog() {
                        return false;
                    }
                    
                    @Override
                    protected void onSuccess(PostcardResult result) {
                        final Postcard postcard = result.getPostcardInfo();
                        if (postcard.Status == 1) {
                            /* deleted */
                            widget.setPostcardImage(R.drawable.discover_card_deleted);
                        } else {
                            if (!DrawableManager.getInstance().fetchDrawableOnThread(postcard.ThumImgUrl, widget.getPostcardImageView()))
                                widget.setPostcardImage(R.drawable.discover_card_loading);
                        }
                        widget.setOnClickListener(new View.OnClickListener() {
                            
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(MessageActivity.this, PostcardActivity.class);
                                intent.putExtra("postcard", postcard);
                                startActivity(intent);
                            }
                        });
                    }
                    
                    @Override
                    protected PostcardResult doRequest() {
                        return ServerFactory.getServer().getPostcardInfo(message.PostcardID);
                    }
                }.execute();
            } else if (3 == message.MessageType) {
                content.setText("TA对你的作品评论了<" + message.Memo + ">");
                new ServerAsyncTask(MessageActivity.this) {
                    
                    protected boolean isShowDialog() {
                        return false;
                    }
                    
                    @Override
                    protected void onSuccess(PostcardResult result) {
                        final Postcard postcard = result.getPostcardInfo();
                        if (postcard.Status == 1) {
                            /* deleted */
                            widget.setPostcardImage(R.drawable.discover_card_deleted);
                        } else {
                            if (!DrawableManager.getInstance().fetchDrawableOnThread(postcard.ThumImgUrl, widget.getPostcardImageView()))
                                widget.setPostcardImage(R.drawable.discover_card_loading);
                        }
                        widget.setOnClickListener(new View.OnClickListener() {
                            
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(MessageActivity.this, PostcardActivity.class);
                                intent.putExtra("postcard", postcard);
                                startActivity(intent);
                            }
                        });
                    }
                    
                    @Override
                    protected PostcardResult doRequest() {
                        return ServerFactory.getServer().getPostcardInfo(message.PostcardID);
                    }
                }.execute();
            }
            date.setText(message.CreatedTime);
            
            icon.setOnClickListener(new View.OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    new ServerAsyncTask(MessageActivity.this) {
                        
                        @Override
                        protected void onSuccess(PostcardResult result) {
                            User detailUser = result.getUser();
                            Intent intent = new Intent(MessageActivity.this, UserActivity.class);
                            intent.putExtra("user", detailUser);
                            intent.putExtra("attention", true);
                            startActivity(intent);
                        }
                        
                        @Override
                        protected PostcardResult doRequest() {
                            return ServerFactory.getServer().getUserInfo("", message.SenderID);
                        }
                    }.execute();
                }
            });

			return convertView;
		}
		
	}
	

}
